'use client';

import React, { useState, useEffect } from 'react';
import { format } from 'date-fns';
import { useCollaboration } from '@/hooks/use-collaboration';
import { Button } from '@/components/ui/button';
import { Card } from '@/components/ui/card';
import { Tabs, TabsContent, TabsList, TabsTrigger } from '@/components/ui/tabs';
import { DocumentVersion } from '@/types/document';
import { Clock, ArrowLeftRight, Check, X, RotateCcw, Diff } from 'lucide-react';
import { toast } from '@/components/ui/use-toast';
import { DiffViewer } from '@/components/editor/diff-viewer';

interface DocumentHistoryProps {
  projectId: string;
  documentId: string;
  className?: string;
}

export function DocumentHistory({ projectId, documentId, className = '' }: DocumentHistoryProps) {
  const { revisions, editor, saveRevision } = useCollaboration();
  const [selectedRevision, setSelectedRevision] = useState<DocumentVersion | null>(null);
  const [compareMode, setCompareMode] = useState(false);
  const [compareRevision, setCompareRevision] = useState<DocumentVersion | null>(null);
  const [diffResult, setDiffResult] = useState<any>(null);
  const [currentTab, setCurrentTab] = useState('history');
  
  // 选择修订版本
  const handleSelectRevision = (revision: DocumentVersion) => {
    if (compareMode) {
      setCompareRevision(revision);
      generateDiff(selectedRevision, revision);
    } else {
      setSelectedRevision(revision);
    }
  };
  
  // 应用修订版本
  const handleApplyRevision = () => {
    if (!selectedRevision || !editor) return;
    
    try {
      // 应用选中的修订版本内容
      editor.commands.setContent(selectedRevision.content);
      
      toast({
        title: '已应用修订版本',
        description: `已恢复到 ${format(new Date(selectedRevision.createdAt), 'yyyy-MM-dd HH:mm')} 的版本`
      });
      
      // 保存一个新的修订版本记录此操作
      saveRevision(selectedRevision.content, `从历史版本恢复 (${format(new Date(selectedRevision.createdAt), 'yyyy-MM-dd HH:mm')})`);
      
      // 重置选择
      setSelectedRevision(null);
    } catch (error) {
      console.error('应用修订版本失败:', error);
      toast({
        title: '操作失败',
        description: '无法应用选中的修订版本',
        variant: 'destructive'
      });
    }
  };
  
  // 取消选择
  const handleCancel = () => {
    setSelectedRevision(null);
    setCompareMode(false);
    setCompareRevision(null);
    setDiffResult(null);
  };
  
  // 进入比较模式
  const handleEnterCompareMode = () => {
    if (!selectedRevision) return;
    setCompareMode(true);
  };
  
  // 生成差异比较
  const generateDiff = (sourceRevision: DocumentVersion | null, targetRevision: DocumentVersion | null) => {
    if (!sourceRevision || !targetRevision) return;
    
    try {
      // 使用更复杂的差异比较逻辑
      // 直接提供源内容和目标内容，由DiffViewer组件负责比较
      
      setDiffResult({
        isDifferent: true, // 初始设置为true，DiffViewer会精确计算
        sourceDate: sourceRevision.createdAt,
        targetDate: targetRevision.createdAt,
        sourceContent: sourceRevision.content,
        targetContent: targetRevision.content,
        sourceVersion: sourceRevision,
        targetVersion: targetRevision
      });
      
      setCurrentTab('compare');
    } catch (error) {
      console.error('生成差异比较失败:', error);
      toast({
        title: '比较失败',
        description: '无法生成版本差异比较',
        variant: 'destructive'
      });
    }
  };
  
  // 合并版本
  const handleMergeVersions = (mergedContent?: any) => {
    if (!editor) return;
    
    try {
      // 使用提供的合并内容或进行简单合并
      const contentToApply = mergedContent || (diffResult.targetContent || diffResult.sourceContent);
      
      // 应用内容
      editor.commands.setContent(contentToApply);
      
      toast({
        title: '已合并版本',
        description: '版本已成功合并'
      });
      
      // 保存一个新的修订版本记录此操作
      saveRevision(
        contentToApply, 
        `合并历史版本 (${format(new Date(diffResult.sourceDate), 'yyyy-MM-dd HH:mm')} 和 ${format(new Date(diffResult.targetDate), 'yyyy-MM-dd HH:mm')})`
      );
      
      // 重置状态
      handleCancel();
    } catch (error) {
      console.error('合并版本失败:', error);
      toast({
        title: '合并失败',
        description: '无法合并选中的版本',
        variant: 'destructive'
      });
    }
  };
  
  // 渲染修订版本列表
  const renderRevisionList = () => {
    if (!revisions || revisions.length === 0) {
      return (
        <div className="py-8 text-center text-muted-foreground">
          <p>暂无历史版本记录</p>
        </div>
      );
    }
    
    return (
      <div className="space-y-2 max-h-[400px] overflow-y-auto pr-2">
        {revisions.map((revision, index) => {
          // 确保revision符合DocumentVersion类型
          const typedRevision: DocumentVersion = {
            id: revision.revision?.id || `temp-${index}`,
            content: revision.revision?.content || {},
            version: revision.revision?.version || 0,
            createdAt: revision.timestamp ? new Date(revision.timestamp).toISOString() : new Date().toISOString(),
            createdBy: revision.revision?.createdBy || { id: '', name: '未知用户' },
            message: revision.revision?.message
          };
          
          return (
            <Card
              key={typedRevision.id}
              className={`p-3 cursor-pointer hover:bg-muted/50 transition-colors ${
                (selectedRevision?.id === typedRevision.id || compareRevision?.id === typedRevision.id) ? 'border-primary bg-muted/50' : ''
              }`}
              onClick={() => handleSelectRevision(typedRevision)}
            >
              <div className="flex items-center justify-between">
                <div className="flex items-center gap-2">
                  <Clock className="h-4 w-4 text-muted-foreground" />
                  <span className="font-medium">
                    {format(new Date(typedRevision.createdAt), 'yyyy-MM-dd HH:mm')}
                  </span>
                </div>
                <div className="text-xs text-muted-foreground">
                  {typedRevision.createdBy?.name || '未知用户'}
                </div>
              </div>
              {typedRevision.message && (
                <p className="text-sm text-muted-foreground mt-1 line-clamp-1">
                  {typedRevision.message}
                </p>
              )}
            </Card>
          );
        })}
      </div>
    );
  };
  
  // 渲染比较结果
  const renderCompareResult = () => {
    if (!diffResult) {
      return (
        <div className="py-8 text-center text-muted-foreground">
          <p>请选择两个版本进行比较</p>
        </div>
      );
    }
    
    return (
      <div className="space-y-4">
        <div className="flex items-center justify-between">
          <div>
            <h4 className="font-medium">比较结果</h4>
            <p className="text-sm text-muted-foreground">
              {format(new Date(diffResult.sourceDate), 'yyyy-MM-dd HH:mm')} 与 
              {format(new Date(diffResult.targetDate), 'yyyy-MM-dd HH:mm')}
            </p>
          </div>
        </div>
        
        <DiffViewer 
          sourceContent={diffResult.sourceContent}
          targetContent={diffResult.targetContent}
          sourceTitle={`版本 ${format(new Date(diffResult.sourceDate), 'yyyy-MM-dd HH:mm')}`}
          targetTitle={`版本 ${format(new Date(diffResult.targetDate), 'yyyy-MM-dd HH:mm')}`}
          onMerge={handleMergeVersions}
          onSelectSource={() => {
            if (diffResult.sourceVersion && editor) {
              editor.commands.setContent(diffResult.sourceVersion.content);
              saveRevision(diffResult.sourceVersion.content, `从历史版本恢复 (${format(new Date(diffResult.sourceVersion.createdAt), 'yyyy-MM-dd HH:mm')})`);
              setSelectedRevision(null);
              setCompareMode(false);
              setCompareRevision(null);
              setDiffResult(null);
              toast({
                title: '已应用版本',
                description: `已恢复到 ${format(new Date(diffResult.sourceVersion.createdAt), 'yyyy-MM-dd HH:mm')} 的版本`
              });
            }
          }}
          onSelectTarget={() => {
            if (diffResult.targetVersion && editor) {
              editor.commands.setContent(diffResult.targetVersion.content);
              saveRevision(diffResult.targetVersion.content, `从历史版本恢复 (${format(new Date(diffResult.targetVersion.createdAt), 'yyyy-MM-dd HH:mm')})`);
              setSelectedRevision(null);
              setCompareMode(false);
              setCompareRevision(null);
              setDiffResult(null);
              toast({
                title: '已应用版本',
                description: `已恢复到 ${format(new Date(diffResult.targetVersion.createdAt), 'yyyy-MM-dd HH:mm')} 的版本`
              });
            }
          }}
        />
      </div>
    );
  };

  return (
    <div className={`space-y-4 ${className}`}>
      <div className="flex items-center justify-between">
        <h3 className="text-lg font-medium">文档历史</h3>
        <div className="flex items-center gap-2">
          {selectedRevision && !compareMode && (
            <>
              <Button onClick={handleApplyRevision} size="sm" variant="default">
                <RotateCcw className="h-4 w-4 mr-1" />
                应用此版本
              </Button>
              <Button onClick={handleEnterCompareMode} size="sm" variant="outline">
                <ArrowLeftRight className="h-4 w-4 mr-1" />
                比较版本
              </Button>
              <Button onClick={handleCancel} size="sm" variant="ghost">
                <X className="h-4 w-4" />
              </Button>
            </>
          )}
          {compareMode && (
            <>
              <div className="text-sm text-muted-foreground">
                {compareRevision ? '已选择两个版本' : '请选择另一个版本进行比较'}
              </div>
              <Button onClick={handleCancel} size="sm" variant="ghost">
                <X className="h-4 w-4" />
                取消比较
              </Button>
            </>
          )}
        </div>
      </div>
      
      {compareMode && compareRevision && (
        <Tabs value={currentTab} onValueChange={setCurrentTab} className="w-full">
          <TabsList className="grid w-full grid-cols-2">
            <TabsTrigger value="history">历史版本</TabsTrigger>
            <TabsTrigger value="compare">比较结果</TabsTrigger>
          </TabsList>
          <TabsContent value="history" className="pt-4">
            {renderRevisionList()}
          </TabsContent>
          <TabsContent value="compare" className="pt-4">
            {renderCompareResult()}
          </TabsContent>
        </Tabs>
      )}
      
      {(!compareMode || !compareRevision) && renderRevisionList()}
    </div>
  );
} 